import { Injectable } from '@nestjs/common';
import { getRepository } from 'typeorm';
import { UserMenu } from './user.menu.entity';
import { Menu } from './menu.entity';

@Injectable()
export class MenuService {
  async getSubMenu(menu) {
    const subMenu = await getRepository(Menu).createQueryBuilder().where('parent_id = :parentId', { parentId: menu.id }).getMany();
    return subMenu;
  }

  async getMenuDataByUserId(id: number) {
    // 获取所有可访问的menu id
    const userMenus = await getRepository(UserMenu).find({ userId: id });
    if (!userMenus) {
      return [];
    }
    // 获取所有一级menu信息
    const menus = await getRepository(Menu)
      .createQueryBuilder()
      .where('id in (:...menuIds)', { menuIds: userMenus.map(item => item.menuId) })
      .orderBy('is_leaf', 'ASC')
      .getMany();
    return menus;
  }
}
